import * as React from 'react';
import { Props, State } from '../type';
import styles from './index.module.less';
import { FilePicker as Picker } from '@/components/file-picker/base';
import _ from 'lodash';

interface FileType {
  id: string;
  url: string;
  size?: number;
  type?: string;
}

export class FilePicker extends React.Component<Props, State> {
  public static defaultProps = new Props();
  public state = new State();

  constructor(props: Props) {
    super(props);
    this.state = {
      receiveData: []
    };
  }

  componentDidMount() {
    this.setReceiveData();
  }

  componentDidUpdate(prevProps) {
    this.setReceiveData(prevProps);
  }

  setReceiveData = (prevProps?: any) => {
    let propsName = 'attachmentIds';
    if (this.props.formValues?.file) {
      propsName = 'file';
    }
    if (prevProps) {
      if (_.eq(prevProps.formValues?.[propsName], this.props.formValues?.[propsName])) return;
      const list = this.props.formValues[propsName] || [];
      return this.setState({
        receiveData: list
      });
    }
    const list = this.props.formValues?.[propsName] || this.props.form?.getFieldValue(this.props.code) || [];
    if (!list.length) return;
    this.setState({
      receiveData: list
    });
  }

  onChange = (value: any) => {
    this.props.form?.setFieldsValue({
      [this.props.code]: value
    });
  };

  render() {
    const { renderMode, form, required } = this.props;
    // console.log('file-picker', this.props, this.state.receiveData);
    return (
      <div
        className={`${styles.itemTitle} ${renderMode === 'detail' ? styles.itemTitleDetail : ''}`}
        {...form?.getFieldProps(this.props.code, {
          trigger: 'onChange',
          rules: [
            { required: required, message: `请选择${this.props.name}` }
          ]
        })}
      >
        <Picker
          // {...this.props}
          name={this.props.name}
          onChange={this.onChange}
          cellProps={{
            receiveData: this.state.receiveData,
            renderMode: renderMode,
            defaultFileType: ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'csv', 'pdf', 'jpe', 'jpg', 'jpeg', 'png', 'gif'],
            defaultFileSize: 50,
            maxFileNumber: 10
          }}
        />
      </div>
    );
  }
}
